package com.study.springcloud;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * @Author raoluping
 * @Date 2017/10/26 13:21
 * @Description
 */
@RestController
public class ConsumerControllerByDiscoveryClient {
  // spring cloud 提供的客户端工具
  @Autowired
  private DiscoveryClient discoveryClient;

  @RequestMapping("/consumerSayHi")
  public String consumerSayHi() {
    // 调用服务器之前，通过eureka client 查询服务的实例信息
    // 也就是说去看 部署了哪些机器，以及IP 端口等信息
    List<ServiceInstance> instances = discoveryClient.getInstances("service-simple-provide");

    if (null == instances || instances.size() == 0) {
      return "504";
    }
    ServiceInstance instance = instances.get(0);

    System.out.println(instance.getServiceId());

    System.out.println(instance.getUri());

    String host = instance.getHost();
    int port = instance.getPort();
    // 模拟http请求
    String result = new RestTemplate()
        .getForObject("http://" + host + ":" + port + "/sayHi?name=hellworld", String.class);
    return result;
  }

}
